﻿using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Chromium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChromeWebTool
{
    public class WebDriverHelper
    {

        static IWebDriver webDriver;
        static int lastUsePort;
        public static void Open(string userNameStr, string passwordStr, Func<string> GetkeyCodeStr, string chromeVersion = "126.0.6478.126")
        {
            var options = new ChromeOptions { Proxy = null };

            options.AddArgument("--disable-extensions");
            options.AddArgument("--disable-gpu");
            options.AddArgument("--no-sandbox");
            options.AddArgument("--disable-dev-shm-usage");
            //options.AddArgument("--headless"); // 可选
            options.AddArgument("--disable-background-networking");
            options.AddArgument("--disable-sync");
            options.AddArgument("--disable-translate");
            options.PageLoadStrategy = PageLoadStrategy.Eager; // 或者None



            //options.AddUserProfilePreference("profile.default_content_setting_values.images", 2);
            //options.AddUserProfilePreference("profile.managed_default_content_settings.stylesheets", 2);

            var driverPath = $"./win64/{chromeVersion}/chromedriver.exe";

            if (!File.Exists(driverPath))
            {
                driverPath = "./win64/126.0.6478.126/chromedriver.exe";
            }

            var chromeDriverService = ChromeDriverService.CreateDefaultService(driverPath);
            if (lastUsePort != 0)
            {
                chromeDriverService.Port = lastUsePort;
            }
            //if (webDriver != null)
            //{
            //    Dispose();
            //}
            if (webDriver == null)
            {
                webDriver = new ChromeDriver(chromeDriverService, options);
                //webDriver = new ChromeDriver(options);
            }

            try
            {
                webDriver.Navigate().GoToUrl("https://cloud-kfs.htsc.com.cn/#/");
                //webDriver.Manage().Window.Maximize();
            }
            catch (Exception)
            {
                chromeDriverService.EnableVerboseLogging = true;
                webDriver = new ChromeDriver(chromeDriverService, options);
                webDriver.Navigate().GoToUrl("https://cloud-kfs.htsc.com.cn/#/");
            }

            // 获取ChromeDriver服务的URL
            var serviceUrl = chromeDriverService.ServiceUrl;
            lastUsePort = serviceUrl.Port;


            // 使用 JavaScript 等待页面完全加载
            var wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(3));
            wait.Until(d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete"));

            //wait.Until(ExpectedConditions.ElementExists(By.Id("elementId"))); // 等待元素存在
            //wait.Until(ExpectedConditions.ElementIsVisible(By.Id("elementId"))); // 等待元素可见

            var userNameEle = webDriver.FindElement(By.XPath("//*[@id=\"username\"]"));
            var passwordEle = webDriver.FindElement(By.XPath("//*[@id=\"password\"]"));
            var keyCodeEle = webDriver.FindElement(By.XPath("//*[@placeholder=\"令牌\"]"));
            var loginEle = webDriver.FindElement(By.XPath("//*[@id=\"login\"]"));
            userNameEle.Clear();
            passwordEle.Clear();
            keyCodeEle.Clear();
            userNameEle.SendKeys(userNameStr);
            passwordEle.SendKeys(passwordStr);
            var keyCodeStr = GetkeyCodeStr?.Invoke() ?? "";
            keyCodeEle.SendKeys(keyCodeStr);

            loginEle.Click();
            //var DownLoadEle = webDriver.FindElement(By.XPath("//*[@id=\"app\"]/div/section/div[1]/ul/li"));
            //DownLoadEle.Click();
        }

        public static void Dispose()
        {
            if (webDriver != null)
            {
                webDriver.Quit();
                webDriver.Dispose();
                webDriver = null;
            }
        }
    }
}
